<template>
  <div class="employee-file-wrapper">
    <a-spin :spinning="spinning">
      <div style="display: flex; justify-content: flex-end; margin-bottom: 12px">
        <a-button icon="plus" type="primary" @click="handleAdd" :disabled="edit != null">新增记录</a-button>
      </div>
      <div v-if="!spinning" style="display: flex; justify-content: flex-start:">
        <a-collapse default-active-key="0" style="width: 100%;">
          <a-collapse-panel v-for="(item, index) in fileData" :key="index" :header="item.eventTime">
            <a-timeline class="file-timeline-wrapper">
              <a-timeline-item v-for="item2 in item.eventByYear" :key="item2.eventTime">
                <div v-for="(item3, index3) in item2.eventByDay" :key="item3.id" class="event-wrapper">
                  <div v-if="index3 === 0" class="event-time-wrapper">
                    <div class="event-month">{{ moment(item2.eventTime).format("MM-DD") }}</div>
                    <div class="event-year">{{ moment(item2.eventTime).format("YYYY") }}</div>
                  </div>
                  <div class="event-bottom-wrapper">
                    <div class="event-title-wrapper">
                      <div class="event-name">{{ item3.eventName }}</div>
                      <div v-if="item3.ifAuto === false">
                        <span
                          style="
                          margin-right: 10px;
                          color: #FF7F7F;
                          cursor: pointer;
                        "
                          @click="handleDelete(item3.id)"
                        >
                          <a-icon type="delete" />
                          <span>删除</span>
                        </span>
                        <span style="color: #929292; cursor: pointer" @click="handleEdit(item, item2, item3)">
                          <a-icon type="edit" />
                          <span>编辑</span>
                        </span>
                      </div>
                    </div>
                    <div class="event-des">{{ item3.description }}</div>
                    <span v-for="(item4, index4) in item3.attachUrl" :key="index4" class="file-display">
                      <a :href="item4.url" download>{{ item4.name }}</a>
                    </span>
                  </div>
                </div>
              </a-timeline-item>
            </a-timeline>
          </a-collapse-panel>
        </a-collapse>
      </div>
    </a-spin>
    <a-modal v-model="eventVisible" :title="isAdd ? '新增记录' : '编辑记录'" @ok="handleOk" @cancel="handleCancel">
      <a-form-model ref="form" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol" label-align="left">
        <a-form-model-item ref="eventName" label="事件名称" prop="eventName">
          <a-input v-model="form.eventName" placeholder="请输入" />
        </a-form-model-item>
        <a-form-model-item ref="eventTime" label="事件时间" prop="eventTime">
          <a-date-picker v-model="form.eventTime" placeholder="请选择" />
        </a-form-model-item>
        <a-form-model-item ref="description" label="备注" prop="description">
          <a-textarea v-model="form.description" placeholder="请输入" :rows="4" />
        </a-form-model-item>
        <a-form-model-item ref="attachUrl" label="附件" prop="attachUrl">
          <div>
            <div v-for="(item, index) in tempList" :key="index">
              <a :href="item.url" download class="mr4" style="color: #6A66F6">{{ item.name }}</a>
              <a-icon type="delete" style="color: #A0A0A0" @click="handleFileDelete(index)" />
            </div>
          </div>
          <div class="employee-file-upload-wrapper">
            <a-upload :custom-request="uploadFile" :multiple="true" :file-list="fileList" @change="handleChange">
              <a-button :disabled="tempList.length < 9 ? false : true"> <a-icon type="plus" />上传文件 </a-button>
            </a-upload>
          </div>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <a-modal v-model="deleteVisible" title="删除记录" @ok="handleDeleteOk">
      <div>您确定要删除记录吗？</div>
    </a-modal>
  </div>
</template>

<script>
import { getEmployeeFile, addPersonalEvent, uploadGeneralFile, updatePersonalEvent, deletePersonalEvent } from "@/api/staff/employeeFile";
import moment from "moment";
export default {
  props: {
    empIdOne: {
      type: String,
      default: ""
    },
    edit: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      spinning: false,
      moment,
      companyId: "",
      fileData: [],
      labelCol: { span: 5 },
      wrapperCol: { span: 14 },
      rules: {
        eventName: [{ required: true, message: "必填", trigger: "blur" }],
        eventTime: [{ required: true, message: "必填", trigger: "change" }]
      },
      form: {
        eventName: "",
        eventTime: "",
        description: "",
        attachUrl: ""
      },
      eventVisible: false,
      deleteVisible: false,
      isAdd: true,
      fileList: [],
      tempList: [],
      tempCount: 0,
      deleteId: ""
    };
  },
  watch: {
    empIdOne: {
      handler(val, oldval) {
        // 现在的刷新
        if (val) {
          this.empId = val;
          this.init();
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.companyId = this.$store.state.hr.companyId;
  },

  methods: {
    // 外部刷新该组件
    refresh(empId) {
      // this.init();
    },
    init() {
      const data = {
        empId: this.empId
      };
      this.spinning = true;
      getEmployeeFile(data)
        .then(res => {
          this.spinning = false;
          this.fileData = res.data;
          this.fileData.forEach((item, index) => {
            item.eventByYear.forEach((item2, index2) => {
              item2.eventByDay.forEach((item3, index3) => {
                if (item3.attachUrl != null) {
                  if (this.isJSON(item3.attachUrl)) {
                    item3.attachUrl = item3.attachUrl ? JSON.parse(item3.attachUrl) : [];
                  } else {
                    // 将自动添加的文件，转换格式
                    const urlArr = item3.attachUrl.split("/");
                    const i = {};
                    i.name = urlArr[urlArr.length - 1];
                    i.url = item3.attachUrl;
                    item3.attachUrl = [];

                    item3.attachUrl.push(i);
                  }
                }
              });
            });
            item.eventByYear.push({
              eventTime: "",
              eventByDay: []
            });
          });
        })
        .catch(err => {
          console.log("debug log --> ", err);
        });
    },
    handleAdd() {
      this.fileList = [];
      this.tempList = [];
      this.tempCount = this.tempList.length;
      this.form = {
        eventName: "",
        eventTime: "",
        description: "",
        attachUrl: ""
      };
      this.eventVisible = true;
      this.isAdd = true;
    },
    isJSON(str) {
      try {
        var obj = JSON.parse(str);
        if (typeof obj === "object" && obj) {
          return true;
        } else {
          return false;
        }
      } catch (e) {
        return false;
      }
    },
    uploadFile(params) {
      this.tempCount += 1;

      if (this.tempCount > 9) {
        this.$message.error("上传数量最多9个");
        return;
      }
      const size = params.file.size / 1024 / 1024;

      if (size > 10) {
        this.$message.error("上传文件大小不应超过10M！");
        return;
      }
      const formData = new FormData();
      formData.append("files", params.file);
      uploadGeneralFile(formData)
        .then(res => {
          const temp = {
            name: params.file.name,
            url: res.data[0]
          };
          this.tempList.push(temp);
          this.tempCount === this.tempList.length;
          params.onSuccess(true);
        })
        .catch(err => {
          console.log("debug log --> ", err);
          params.onError(true);
        });
    },
    handleChange(info) {
      this.fileList = info.fileList;
    },
    handleOk() {
      this.form.attachUrl = this.tempList.map((item, index) => {
        return {
          name: item.name,
          url: item.url
        };
      });
      const data = {
        ...this.form,
        companyId: this.companyId,
        empId: this.empId,
        eventType: 12,
        ifAuto: false,
        companyName: this.$store.state.hr.companyName
      };
      data.eventTime = moment(data.eventTime).format("YYYY-MM-DD HH:mm:ss");
      data.attachUrl = JSON.stringify(data.attachUrl);
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.isAdd) {
            addPersonalEvent(data)
              .then(res => {
                this.init();
                this.eventVisible = false;
              })
              .catch(err => {
                console.log("debug log --> ", err);
              });
          } else {
            updatePersonalEvent(data)
              .then(res => {
                this.init();
                this.eventVisible = false;
              })
              .catch(err => {
                console.log("debug log --> ", err);
              });
          }
        }
      });
    },
    handleCancel() {
      this.fileList = [];
      this.tempList = [];
      this.tempCount = this.tempList.length;
      this.form = {
        eventName: "",
        eventTime: "",
        description: "",
        attachUrl: ""
      };
      this.$refs.form.resetFields();
    },
    handleDelete(id) {
      this.deleteId = id;
      this.deleteVisible = true;
    },
    handleEdit(item, item2, item3) {
      this.form.eventTime = moment(item2.eventTime);
      this.form.eventName = item3.eventName;
      this.form.description = item3.description;
      this.form.id = item3.id;
      this.tempList = JSON.parse(JSON.stringify(item3.attachUrl));
      this.tempCount = this.tempList.length;
      this.eventVisible = true;

      this.isAdd = false;
    },
    handleFileDelete(index) {
      this.tempList.splice(index, 1);
      this.tempCount = this.tempList.length;
    },
    handleDeleteOk() {
      deletePersonalEvent(this.deleteId)
        .then(res => {
          this.$message.success("删除成功");
          this.init();
        })
        .catch(err => {
          console.log("debug log --> ", err);
        });
      this.deleteVisible = false;
    }
  }
};
</script>

<style scoped lang="scss">
.employee-file-upload-wrapper ::v-deep .ant-upload-list {
  display: none;
}
.employee-file-wrapper {
  .ant-timeline-item {
    padding: 0;
  }
  .file-timeline-wrapper {
    padding-left: 50px;
  }
  .event-wrapper {
    .event-time-wrapper {
      position: relative;
      right: 75px;
      .event-month {
        color: #252525;
        font-size: 16px;
      }
      .event-year {
        color: #a1a1a1;
        font-size: 12px;
        margin-left: 13px;
      }
    }
    .event-bottom-wrapper {
      // margin-bottom: 20px;
      position: relative;
      bottom: 10px;
      .event-title-wrapper {
        display: flex;
        justify-content: space-between;
      }
      .event-name {
        color: #252525;
        font-size: 14px;
        font-weight: 700;
      }
      .event-des {
        color: #777777;
        font-size: 14px;
        text-indent: 2;
      }
    }
    .file-display {
      color: var(--primary);
      margin-right: 20px;
      display: inline-block;
    }
  }
}
</style>
